package cn.nebula.music.controller;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.nebula.music.domain.Picture;
import cn.nebula.music.service.PictureService;

@Controller
public class PictureController {

	@Autowired
	private PictureService pictureService;

	@RequestMapping("/editPicture")
	@ResponseBody
	public Map<String, Object> editPicture(@RequestParam Integer id) throws Exception {
		Map<String, Object> values = new HashMap<String, Object>();
		values.put("picture", pictureService.findPictureById(id));
		return values;
	}

	@RequestMapping("/listAllPictures")
	@ResponseBody
	public Map<String, Object> listAllPictures() throws Exception {
		Map<String, Object> values = new HashMap<String, Object>();
		values.put("pictures", pictureService.findAllPicturesOfBT());
		return values;
	}

	@RequestMapping("/newPicture")
	@ResponseBody
	public Map<String, Object> newPicture() throws Exception {
		Map<String, Object> values = new HashMap<>();
		return values;
	}

	@RequestMapping("/updatePicture")
	@ResponseBody
	public boolean updatePicture(@RequestBody Picture picture) throws Exception {
		pictureService.updatePicture(picture);
		return true;
	}

	@RequestMapping("/addPicture")
	@ResponseBody
	public boolean addPicture(@RequestBody Picture picture) throws Exception {
		pictureService.addPicture(picture);
		return true;
	}

	@RequestMapping("/deletePicture")
	@ResponseBody
	public boolean deletePicture(@RequestParam Integer id) throws Exception {
		pictureService.deletePictureById(id);
		return true;
	}

	@RequestMapping("/uploadPicture")
	@ResponseBody
	public void uploadPicture(HttpServletRequest request, HttpServletResponse resp) {
		try {
			String path = "d:\\Program Files\\nebula\\picture";
			File dir = new File(path);
			if (!dir.exists()) {
				dir.mkdirs();
			}
			Part part = request.getPart("file");
			InputStream inputStream = part.getInputStream();
			OutputStream outputStream = null;
			outputStream = new FileOutputStream(path + "\\" + part.getSubmittedFileName());
			int ch = 0;
			while ((ch = inputStream.read()) != -1) {
				outputStream.write(ch);
			}
			outputStream.close();
			inputStream.close();
		} catch (Exception e) {
			e.printStackTrace();

		}
	}
}
